package com.pocketmenu.persistence;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.pocketmenu.business.Constants;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class IngredientDataSource {
		
	private IngredientDataSource h=this;
	// Database fields
	  private SQLiteDatabase database;
	  private SQLiteHelper dbHelper;
	  private String[] allColumns = 
		  { SQLiteHelper.COLUMN_ID,
			SQLiteHelper.COLUMN_INGREDIENT_NAME};

	  private SoapPrimitive resultado;
	  private boolean waitingForThread = true;
	  private boolean success = true;
	  
	  public IngredientDataSource(Context context) {
	    dbHelper = new SQLiteHelper(context);
	  }

	  public void open() throws SQLException {
	    database = dbHelper.getWritableDatabase();
	  }

	  public void close() {
	    dbHelper.close();
	  }

	  public Ingredient create(String name) {
	    ContentValues values = new ContentValues();
	    values.put(SQLiteHelper.COLUMN_INGREDIENT_NAME, name);	   
	    
	    long insertId = database.insert(SQLiteHelper.TABLE_INGREDIENT, null,
	        values);
	    
	    Cursor cursor = database.query(SQLiteHelper.TABLE_INGREDIENT,
	        allColumns, SQLiteHelper.COLUMN_ID + " = " + insertId, null,
	        null, null, null);
	    cursor.moveToFirst();
	    Ingredient newTemp = cursorToObject(cursor);
	    cursor.close();
	    return newTemp;
	  }

	  public void delete(Ingredient toDelete) {
	    int id = toDelete.getId();
	    System.out.println("Ingredient deleted with id: " + id);
	    database.delete(SQLiteHelper.TABLE_INGREDIENT, SQLiteHelper.COLUMN_ID
	        + " = " + id, null);
	  }

	  public List<Ingredient> getAll() {
	    List<Ingredient> listTemp = new ArrayList<Ingredient>();

	    Cursor cursor = database.query(SQLiteHelper.TABLE_INGREDIENT,
	        allColumns, null, null, null, null, null);

	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	      Ingredient temp = cursorToObject(cursor);
	      listTemp.add(temp);
	      cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
	    return listTemp;
	  }
	  
	  
	  public Ingredient getIngredientByName(String name) {
		    Ingredient buscado=null;
		    Log.i("system.out", "entramos");
		    Cursor cursor = database.query(SQLiteHelper.TABLE_INGREDIENT,
		        allColumns, SQLiteHelper.COLUMN_INGREDIENT_NAME+ " = '"+name+"'", null, null, null, null);
		    Log.i("system.out", "aqui si es: "+cursor.getCount()+" nombre: "+name);
		    cursor.moveToFirst();
		    while (!cursor.isAfterLast() && buscado==null) {
		      buscado = cursorToObject(cursor);
		     
		      cursor.moveToNext();
		    }
		    // Make sure to close the cursor
		    cursor.close();
		    return buscado;
		  }
	  
	  
	  
	  public List<String> getAllNames() {
		    List<String> listTemp = new ArrayList<String>();
		    
		    Cursor cursor = database.query(SQLiteHelper.TABLE_INGREDIENT,
		        allColumns, null, null, null, null, null);
		    
		    
		    cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		      
		      listTemp.add(cursor.getString(1));
		      cursor.moveToNext();
		    }
		    // Make sure to close the cursor
		    cursor.close();
		    return listTemp;
		  }
	  

	  private Ingredient cursorToObject(Cursor cursor) {
	    Ingredient temp = new Ingredient();
	    temp.setId(cursor.getInt(0));
	    temp.setName(cursor.getString(1));	    
	    return temp;
	  }	  	  
	  
	  public boolean loadFromWeb(){
		  Thread networkThread = new Thread() {
      	    @Override
      	    public void run() {
	      	      
	  	    	//request       	    
	      	    String metodo = "select";	
	      	    SoapObject request= new SoapObject(Constants.namespace, metodo);
	      	    request.addProperty("tabla", "Ingredient");
	
	      	    //modelo sobre
	      	    SoapSerializationEnvelope sobre= new SoapSerializationEnvelope(SoapEnvelope.VER11);
	      	    sobre.dotNet = true;
	
	      	    sobre.setOutputSoapObject(request);
	
	      	    //transporte
	      	    HttpTransportSE transporte= new HttpTransportSE(Constants.url,10000);	          
	      	    transporte.debug = true;           
	
	      	    //llamada
	      	    try {
	      	    	transporte.call(Constants.namespace+metodo, sobre);
		   			
		   			//resultado
		   			resultado = (SoapPrimitive) sobre.getResponse();	   					   			
			   		success = true;
			   		
		   			} catch (Exception e) {
	   					Log.i("App.err " + getClass().getSimpleName(), e.getMessage());
		   				e.printStackTrace();
		   				success = false;
		   			}
	      	    waitingForThread = false;
      	    }	      	      
  	    };
  	    networkThread.start();
  	    
  	    while(waitingForThread){	      	    	
  	    }
  	    
  	    if(success)
  	    	return loadDataToDatabase();
  	    else
  	    	return false;
	  }
	  
	  private boolean loadDataToDatabase()
	  {
		  try
		  {						
			String respuesta=resultado.toString();
			String[] restaurantesWeb = respuesta.split(";");
				
			database.execSQL("DROP TABLE IF EXISTS " + SQLiteHelper.TABLE_INGREDIENT);
			database.execSQL(SQLiteHelper.TABLE_CREATE_INGREDIENT);
			
			for(int i=0;i<restaurantesWeb.length;i++){
				String[] restauranteWebActual=restaurantesWeb[i].split("\\*");
				h.create(restauranteWebActual[1]);				
			}
			success = true;
			Log.i("App.log " + getClass().getSimpleName(), "Exito");
		  }
		  catch(Exception e)
		  {
			  Log.i("App.err " + getClass().getSimpleName(), e.getMessage());
			  e.printStackTrace();
			  success = false;
		  }
		  
		  return success;
	  }	  
}
